#!/usr/bin/env python
# coding: utf-8

import os,sys
import re
import glob
import shutil

SECTIONS = {
		'habitation': (
			r'#street name dictionary start',
			r'#district name dictionary end'
			),
		'num1':(
			r'#1 digit number dictionary start',
			r'#1 digit number dictionary end'
			),
		'num3':(
			r'#3 digit number dictionary start',
			r'#3 digit number dictionary end'
			),
		'num4':(
			r'#4 digit number dictionary start',
			r'#4 digit number dictionary end'
			),
		'num5':(
			r'#5 digit number dictionary start',
			r'#5 digit number dictionary end'
			),
		'landline':(
			r'#landline dictionary start',
			r'#landline dictionary end'
			),
		'mobile_phone_number':(
			r'#mobile phone number(13digit) dictionary start',
			r'#mobile phone number(13digit) dictionary end'
			),
		'landline1':(
			r'#landline1 dictionary start',
			r'#landline1 dictionary end'
			),
		'num34':(
			r'#3 or 4 digit number dictionary start',
			r'#3 or 4 digit number dictionary end'
			),
		'num345':(
			r'#3,4,5 Digit dictionary start',
			r'#3,4,5 Digit dictionary end'
			),
		'num789':(
			r'#7,8,9 Digit dictionary start',
			r'#7,8,9 Digit dictionary end'
			),
		'num101112':(
			r'#10,11,12 Digit dictionary start',
			r'#10,11,12 Digit dictionary end'
			)
}

START_LINE = r'#street name dictionary start'
END_LINE = r'#district name dictionary end'
target_dir_no = {'Beijing':0, 'Gan':50, 'Kejia':40, 'Min':10, 'Wu':30, 'Xiang':60, 'Yue':20}

class CannotFindError(Exception): pass

def WriteCtlFile(ctlpath, ctlfn, tplfn, startLineC, endLineC):
	# get A:str
	A = ctlpath

	# lines from template.ctl
	ctllines = open(tplfn).readlines()

	# get B:int, C:str
	r = re.match(r'speaker(\d{1,2})([^.]*)\.ctl', ctlfn)
	B = r.groups()[0]
	B = int(B)
	C = r.groups()[1]

	# delete lines
	all_start_lino = FindLino(ctllines, r'user\s*edit\s*section\s*start')
	all_end_lino = FindLino(ctllines, r'user\s*edit\s*section\s*end')
	st_lino = FindLino(ctllines, startLineC)
	end_lino = FindLino(ctllines, endLineC)
	ctllines[end_lino+1:all_end_lino]=[]
	ctllines[all_start_lino+1:st_lino]=[]

	# process lines
	st_lino = FindLino(ctllines, startLineC)
	end_lino = FindLino(ctllines, endLineC)
	for n in range(st_lino, end_lino):

		# need process determine
		sline = ctllines[n]
		r = re.match(
				r'\s*Reco\s*\(\s*speaker(\d+)_unicode[^\)]*\)\s*\.\.\\([^\\]+)\\([^\\]+)\\([^\\]*)\\', 
				sline)
		if r:
			# make D:int, E:str, F:str, G:str
			D = r.groups()[0]
			D = int(D)
			E = A
			F = B + target_dir_no[A]
			F = str(F).zfill(3)
			G = "C1" if C=="" else C[1:]
			if 1<=B<=5:
				D = B
			elif 6<=B<=10:
				D = B-5
			sline = re.sub(r'\.\.\\[^\\]+\\[^\\]+\\[^\\]+\\', 
						r'..\\' + E + r'\\' + F + r'\\' + G + r'\\',
						sline)
			sline = re.sub(r'(?<=speaker)\d*(?=_unicode)', str(D), sline)
			ctllines[n] = sline
	# write to file
	of = open(ctlpath+'\\'+ctlfn,'w')
	of.writelines(ctllines)
	of.close()



def FindLino(lines, s):
	for n in range(len(lines)):
		if lines[n].find(s)>=0:
			return n
	for n in range(len(lines)):
		if re.search(s,lines[n]):
			return n
	raise CannotFindError()

def ProcSectionFiles(sn):
	LogPrint(r'processing section: '+ sn)
	for dir in target_dir_no.keys():
		for fn in glob.glob(dir + r'\*.ctl'):
			LogPrint(fn)
			WriteCtlFile(dir, fn.split('\\')[1], r'template.ctl', SECTIONS[sn][0], SECTIONS[sn][1])

def RunEvalVoice():
	os.system(r'Go_All.bat')

# copy .res file to ResArchive\
def PlaceRes(sn):
	res_ar_fold = "ResArchive"
	if not os.path.exists(res_ar_fold):
		os.mkdir(res_ar_fold)
	if not os.path.exists(os.path.join(res_ar_fold, sn)):
		os.mkdir( os.path.join(res_ar_fold, sn))
	for fres in glob.glob(r'*\*.res'):
		foldn = fres.split('\\')[0]
		filen = fres.split('\\')[1]
		if not os.path.exists(os.path.join(res_ar_fold, sn, foldn)):
				os.mkdir(os.path.join(res_ar_fold, sn, foldn))
		shutil.move(fres, os.path.join(res_ar_fold, sn, fres))		
		LogPrint( "move " + fres + " to " + os.path.join(res_ar_fold, sn, fres))
	for flog in glob.glob(r'*\*.log'):
		foldn = flog.split('\\')[0]
		filen = flog.split('\\')[1]
		if not os.path.exists(os.path.join(res_ar_fold, sn, foldn)):
				os.mkdir(os.path.join(res_ar_fold, sn, foldn))
		shutil.move(flog, os.path.join(res_ar_fold, sn, flog))		
		LogPrint( "move " + flog + " to " + os.path.join(res_ar_fold, sn, flog))
	for fctl in glob.glob(r'*\*.ctl'):
		foldn = fctl.split('\\')[0]
		filen = fctl.split('\\')[1]
		if not os.path.exists(os.path.join(res_ar_fold, sn, foldn)):
				os.mkdir(os.path.join(res_ar_fold, sn, foldn))
		shutil.copyfile(fctl, os.path.join(res_ar_fold, sn, fctl))		
		LogPrint( "copy " + fctl + " to " + os.path.join(res_ar_fold, sn, fctl))
		


LOG_FILE = open('ProcCtl.log', 'w')
def LogPrint(s):
	print s
	print >> LOG_FILE, s

def __main__():
	for sn in SECTIONS.keys():
		ProcSectionFiles(sn)
		LogPrint('\n\n\n\n')
		RunEvalVoice()
		LogPrint('\n\n\n\n')
		PlaceRes(sn)
		LogPrint('\n\n\n\n')

#	PlaceRes(r'habitation')
#	lines = open(r'template.ctl','r').readlines()
#	for k in SECTIONS.keys():
#		for li in SECTIONS[k]:
#			print li + r'  ==>> ' + str(FindLino(lines, li))
#	return

#	for dir in target_dir_no.keys():
#		for fn in glob.glob(dir + r'\*.ctl'):
#			print fn
#			WriteCtlFile(dir, fn.split('\\')[1], r'template.ctl', START_LINE, END_LINE)


if __name__ == '__main__':
	__main__()



